package org.easy.http.client.resouce;

import org.easy.http.client.util.ClassLoaderUtils;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Description TODO
 * @Author WuXueLi
 * @Date 16:53 2023/2/4
 * @Version 1.0
 **/
public class EasyDefaultResourceDescriptorLoader implements EasyResourceDescriptorLoader{

    private ClassLoader classLoader;

    public EasyDefaultResourceDescriptorLoader () {
        this(ClassLoaderUtils.getDefaultClassLoader());
    }

    public EasyDefaultResourceDescriptorLoader (ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public EasyResourceDescriptor getResourceDescriptor(String location) {
        if (location.startsWith(CLASSPATH_URL_PREFIX)) {
            return new EasyClassPathResourceDescriptor(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
        } else {
            try {
                // Try to parse the location as a URL...
                URL url = new URL(location);
                return new EasyURLResourceDescriptor(url);
            } catch (MalformedURLException ex) {
                return new EasyFileSystemResourceDescriptor(location);
            }
        }
    }

    @Override
    public ClassLoader getClassLoader() {
        return  (this.classLoader != null ? this.classLoader : ClassLoaderUtils.getDefaultClassLoader());
    }

    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }
}
